import StringTemplate from './stringTemplate.js'
import JSZip from 'jszip'
function getGlobalVars(obj) {
    let res = {
        save() { }
    }
    return Object.assign(res, obj)
}

function generatePath(files, keys, filename, content) {
    if (keys.length === 0) {
        files[filename] = content
    } else {
        let key = keys.shift()
        let obj
        if (files[key]) {
            obj = files[key]
        } else {
            obj = {}
            files[key] = obj
        }
        generatePath(obj, keys, filename, content)
    }
}

export function getDirContent(templates,vars,logs) {
    vars=vars||{}
    let files = {}
    templates.forEach(template => {
        console.log(template)
        let $path = []
        let $filename = []
        function save(path, filename) {
            if(path&&filename){
                $path.push(path)
                $filename.push(filename)
            }else{
                throw new Error("保存文件错误，请检查文件名格式")
            }
        }
        let res = new StringTemplate(template).render(getGlobalVars(Object.assign({
            save
        },vars)))
        console.log(res)
        for(let i=0,l=$path.length;i<l;i++){
            let p=$path[i]
            let f=$filename[i]
            generatePath(files, p.split("/"), f, res.res)
        }
        if(logs){
            logs.push(res.logs)
        }
    })
    console.log(files)
    return files
}

export function render(template,view) {
    view=view||{}
    let res = new StringTemplate(template).render(getGlobalVars(view))
    return res
}

function createZipFileContent(zip, fileContent, parentDir) {
    for (let key in fileContent) {

        if (typeof fileContent[key] === 'string') {
            zip.file(parentDir + "/" + key, fileContent[key])
        } else {
            if (parentDir) {
                createZipFileContent(zip, fileContent[key], parentDir + "/" + key)
            } else {
                createZipFileContent(zip, fileContent[key], key)
            }
        }
    }
}
export function createZip(zip,fileContent) {
    if(!zip){
        zip=new JSZip()
    }
    if(fileContent){
        createZipFileContent(zip, fileContent, "")
    }
    return zip
}